﻿package demo.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class BaseDao {

	protected Connection con = null;
	protected PreparedStatement ps = null;
	protected ResultSet rs = null;
	//	
	// //获取连接
	// protected void openConnection(){
	// try {
	// Context ctx = new InitialContext();
	// DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/Message");
	// con = ds.getConnection();
	// } catch (NamingException e) {
	// e.printStackTrace();
	// } catch (SQLException e) {
	// e.printStackTrace();
	// }
	// }
	private static String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";// 数据库驱动字符串
	private static String url = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=BBS_Message";// 连接URL字符串
	private static String user = "sa"; // 数据库用户名
	private static String password = "hr"; // 用户密码

	/**
	 * 获取数据库连接对象。
	 */
	public Connection openConnection() {
		//Connection con = null;// 数据连接对象
		try {
			if (con == null||con.isClosed()) {
				// 获取连接并捕获异常
				try {
					Class.forName(driver);
					con = DriverManager.getConnection(url, user, password);
				} catch (Exception e) {
					e.printStackTrace();// 异常处理
				}
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return con;// 返回连接对象
	}

	// 更新新据库
	public int executeUpdata(String sql, List<Object> list) {
		con=openConnection();
		try {
			ps = con.prepareStatement(sql);
			if (list == null)
				return ps.executeUpdate();
			int i = 1;
			for (Object obj : list) {
				ps.setObject(i, obj);
				i++;
			}
			return ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			closeResource();
		}
		return 0;
	}

	// 关闭流
	protected void closeResource() {
		try {
			if (rs != null)
				rs.close();
			if (ps != null)
				ps.close();
			if (con != null)
				con.close();

		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
